<?php

namespace App\Api\Controllers\HuiPay;


use App\Api\Controllers\BaseController;
use App\Api\Controllers\Config\TfConfigController;
use App\Common\PaySuccessAction;
use App\Common\RefundSuccessAction;
use App\Models\MerchantWalletDetail;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\RefundOrder;
use App\Models\Store;
use App\Models\StorePayWay;
use App\Models\TfStore;
use App\Models\UserRate;
use App\Models\UserWalletDetail;
use App\Services\Pay\PayService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;
use MyBank\Tools;

class NotifyController extends BaseController
{
    //汇付-回调
    public function pay_notify_url(Request $request)
    {
        try {
            $data = $request->all();
//            Log::info('汇付交易回调');
//            Log::info($data);  //返回的是数组
//            [
//                'data' => '{"bank_code":"SUCCESS","trans_date":"20200109","extension":"","device_id":"SMSM34358719666880610","bank_message":"交易成功","trans_time":"114324","trans_amt":"0.01","service_amt":"0.00","platform_seq_id":"84027092336902144","out_trans_id":"4200000493202001096834196621","party_order_id":"MCS0000001200109114327dhg0vcz9Vx","mer_priv":"","pay_type":"W0","cust_id":"6666000001036124","order_id":"wxscan20200109114324489652418","fee_amt":"0.00"}',
//                'resp_desc' => '000000',
//                'sign' => 'q70XAJnY azGsHC8cPdf2YMnvO5R0B4cUI FMxFAvK1zyaAOmqlN3YHjqXkSijXLN42hoyBoCZURnEjc3NvOeYT S9aPR kmezDNl4RTg9/eIbLKXcXz262D0 v5RgZxCA6HLCzlYVAfUr VvGNXZhn0x0xKov6V/bmCzLjofU hOyWbwxEgqIHllG vpAOfvRrlkD6rvbaaP2x4Nh5jfg3mLr3Wy4W8WEQgWQqduyOct/dgrFWSDDxQ3xqzq bTS oRvB mMDLdAZUTn 7xFNTar0xwpZ50z/3BpWyGq0qbW0PAx2AiUs5sFFwFlVtesYuHAdJxYnEGNyyLJzC42Q==',
//                'resp_code' => '交易成功',
//            ]
            if (isset($data) && !empty($data)) {
//                $data = json_decode($data, true);
                if ($data['resp_code'] == '000000') {
                    if (isset($data['data']) && !empty($data['data'])) {
                        $return_data = json_decode($data['data'], true);

                        if (isset($return_data['bank_code']) && ($return_data['bank_code'] == 'SUCCESS')) {
                            if (isset($return_data['order_id']) && !empty($return_data['order_id'])) {
                                $out_trade_no = $return_data['order_id'];
                                if (Schema::hasTable('order_items')) {
                                    $order = OrderItem::where('out_trade_no', $out_trade_no)->first();
                                } else {
                                    $order = Order::where('out_trade_no', $out_trade_no)->first();
                                }

                                //订单存在
                                if ($order) {
                                    //系统订单未成功
                                    if ($order->pay_status == 2) {
                                        $trans_date = isset($return_data['trans_date'])?date('Y-m-d', strtotime($return_data['trans_date'])):'';
                                        $trans_time = isset($return_data['trans_time'])?date('H:i:s', strtotime($return_data['trans_time'])):'';
                                        $trade_no = $return_data['party_order_id']??'';
                                        $pay_time = $trans_date.' '.$trans_time;
                                        $buyer_pay_amount = $return_data['trans_amt'];
//                                        $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', ''); //此处不是浮点会报错
//                            $buyer_id = $data['buyerId'];
                                        $in_data = [
                                            'status' => '1',
                                            'pay_status' => 1,
                                            'pay_status_desc' => '支付成功',
                                            'trade_no' => $trade_no,
                                            'pay_time' => $pay_time,
//                                            'buyer_id' => $buyer_id,
                                            'buyer_pay_amount' => $buyer_pay_amount,
                                            'total_amount' => $buyer_pay_amount,
                                        ];
                                        Order::where('out_trade_no', $out_trade_no)->update($in_data);
                                        if (Schema::hasTable('order_items')) {
                                            OrderItem::where('out_trade_no', $out_trade_no)->update($in_data);
                                        }

                                        if (strpos($out_trade_no, 'scan')) {

                                        } else {
                                            //支付成功后的动作
                                            $data = [
                                                'ways_type' => $order->ways_type,
                                                'company' => $order->company,
                                                'ways_type_desc' => $order->ways_type_desc,
                                                'source_type' => '18000', //返佣来源
                                                'source_desc' => '汇付', //返佣来源说明
                                                'total_amount' => $order->total_amount,
                                                'out_trade_no' => $order->out_trade_no,
                                                'other_no' => $order->other_no,
                                                'rate' => $order->rate,
                                                'fee_amount' => $order->fee_amount,
                                                'merchant_id' => $order->merchant_id,
                                                'store_id' => $order->store_id,
                                                'user_id' => $order->user_id,
                                                'config_id' => $order->config_id,
                                                'store_name' => $order->store_name,
                                                'ways_source' => $order->ways_source,
                                                'pay_time' => $pay_time,
                                                'device_id' => $order->device_id,
                                            ];
                                            PaySuccessAction::action($data);
                                        }
                                    } else {
                                        //系统订单已经成功了
                                    }
                                }
                            } else {
//                                Log::info('交易回调无订单号返回');
                            }
                        } else {
                            return json_encode([
                                'code' => $return_data['bank_code'],
                                'msg' => $return_data['bank_message'],
                            ]);
                        }

                        return json_encode([
                            'code' => 'success',
                            'msg' => "成功",
                        ]);
                    } else {
//                        Log::info('交易回调没有data值返回');
                        return json_encode([
                            'code' => $data['resp_code'],
                            'msg' => $data['resp_desc'],
                        ]);
                    }

                } else {
                    return json_encode([
                        'code' => $data['resp_code'],
                        'msg' => $data['resp_desc'],
                    ]);
                }
            }
            return json_encode([
                'code' => 'fail',
                'msg' => "汇付没有回调交易参数",
            ]);
        } catch (\Exception $exception) {
            Log::info('汇付交易异步报错');
            Log::info($exception);
        }
    }

    //汇付-退款回调
    public function return_pay_notify_url(Request $request)
    {
        try {
            $data = $request->all();
//            Log::info('汇付退款回调');
//            Log::info($data); //数组
//            $data = [
//                'data' => '{"trans_date":"20200111","extension":"","business_amt":"0.01","device_id":"SMSM34358719666880610","refund_amt":"0.01","trans_time":"111321","platform_seq_id":"84744302769995776","mer_priv":"","pay_type":"W0","cust_id":"6666000001036124","order_id":"wxscan20200111111227572222825"}',
//                'resp_desc' => '000000',
//                'sign' => 'jfbtqrQdieOizRD8Nl1a1pDpcuB4mkj8WTlz3gHk77g58Bj/6o3xV9vtdcuhVkBCc8dGAgOOqln9gIqBXKIghrFTHtkjb48sUWDplctoITzWNX3Y2H090d8oB0cHAmCN0vVWWwZb3MfmgyinOqYchaFLJD DJ PWB06HIsK/mO4V1EHSdT/vVY VfFAbu8xynKSGlxPmhRJ3iq10A29BTZki4KkiC23YgETLjoLzGTPZEEok0kD2409OcGPagCotl/cSIHr7fxXOuv/Qn0n2bbctG/UXsH NM2Xt0a4ndEFefeM4ciB9215q0AEySS2Mh7EGvoiYV31JXfjDr2sWbQ==',
//                'resp_code' => '交易成功',
//            ];
            if (isset($data) && !empty($data)) {
//                $data = json_decode($data, true);
                //汇付退款成功
                if ($data['resp_desc'] == '000000') {
                    if (isset($data['data']) && !empty($data['data'])) {
                        $return_data = json_decode($data['data'], true);

                        //订单是否存在
                        if (isset($return_data['order_id'])) {
                            $out_trade_no = $return_data['order_id'];
                            if (Schema::hasTable('order_items')) {
                                $order = OrderItem::where('out_trade_no', $out_trade_no)->first();
                            } else {
                                $order = Order::where('out_trade_no', $out_trade_no)->first();
                            }

                            //订单存在
                            if ($order) {
                                //系统订单退款中
                                if ($order->pay_status == 5) {
                                    $trans_date = isset($return_data['trans_date'])?date('Y-m-d', strtotime($return_data['trans_date'])):'';
                                    $trans_time = isset($return_data['trans_time'])?date('H:i:s', strtotime($return_data['trans_time'])):'';
                                    $trade_no = $return_data['party_order_id']??'';
                                    $pay_time = $trans_date.' '.$trans_time;
                                    $buyer_pay_amount = isset($return_data['business_amt'])?$return_data['business_amt']:$return_data['refund_amt']; //实际退款金额
                                    $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');
//                            $buyer_id = $data['buyerId'];
                                    $in_data = [
                                        'status' => '6',
                                        'pay_status' => 6,
                                        'pay_status_desc' => '已退款',
                                        'trade_no' => $trade_no,
                                        'pay_time' => $pay_time,
//                                        'buyer_id' => $buyer_id,
                                        'refund_amount' => $buyer_pay_amount,
                                    ];
                                    $update_re = Order::where('out_trade_no', $out_trade_no)->update($in_data);
                                    if (Schema::hasTable('order_items')) {
                                        $update_re = OrderItem::where('out_trade_no', $out_trade_no)->update($in_data);
                                    }
                                    if (!$update_re) {
//                                        Log::info('汇付退款回调，更新系统订单号失败');
//                                        Log::info($in_data);
                                    }

                                    //记录入退款表
                                    RefundOrder::create([
                                        'ways_source' => $order->ways_source,
                                        'type' => $order->ways_type,
                                        'refund_amount' => $order->total_amount,//退款金额
                                        'refund_no' => $out_trade_no . '123',//退款单号
                                        'store_id' => $order->store_id,
                                        'merchant_id' => $order->merchant_id,
                                        'out_trade_no' => $order->out_trade_no,
                                        'trade_no' => $order->trade_no
                                    ]);
                                    //退款成功后的操作
                                    RefundSuccessAction::action([
                                        'out_trade_no'=>$out_trade_no,
                                        'refund_no' => $out_trade_no . '123',//退款单号
                                    ]);
                                    //返佣去掉
                                    UserWalletDetail::where('out_trade_no', $out_trade_no)->update([
                                        'settlement' => '03',
                                        'settlement_desc' => '退款订单',
                                    ]);
                                    MerchantWalletDetail::where('out_trade_no', $out_trade_no)->update([
                                        'settlement' => '03',
                                        'settlement_desc' => '退款订单',
                                    ]);
                                } else {
//                                    Log::info('汇付退款回调，没有正在退款的该系统订单号');
                                }
                            } else {
//                                Log::info('汇付退款回调，没有找到系统订单号');
                            }
                        } else {
//                            Log::info('汇付退款回调，没有返回订单号');
                        }

                        return json_encode([
                            'code' => 'success',
                            'msg' => "成功",
                        ]);
                    } else {
                        return json_encode([
                            'code' => $data['resp_desc'],
                            'msg' => $data['resp_code'],
                        ]);
                    }

                } elseif($data['resp_desc'] == '000001') {
                    if (isset($data['data']) && !empty($data['data'])) {
                        //如果汇付回调结果还是处理中，先查询退款结果，结果成功则成功，失败则失败
                        $return_json_data = json_decode($data['data'], true);
                        $huipay_obj = new PayController();
                        $out_trade_no = $return_json_data['order_id'];
                        $cust_id = $return_json_data['cust_id']; //用户客户号
                        $device_id = $return_json_data['device_id'];
                        $return_select = [
                            'out_trade_no' => $out_trade_no,
                            'mer_cust_id' => $cust_id,
                            'device_id' => $device_id,
                        ];
                        $return_select_res = $huipay_obj->refund_query($return_select); //0-系统错误 1-成功 2-正在退款 3-失败 4-初始
                        if ($return_select_res['status'] == '1') {
                            if (isset($return_select_res['data']) && !empty($return_select_res['data'])) {
                                //凭条存在退款订单
                                if (isset($return_select_res['order_id'])) {
                                    $out_trade_no = $return_select_res['order_id'];
                                    if (Schema::hasTable('order_items')) {
                                        $order = OrderItem::where('out_trade_no', $out_trade_no)->first();
                                    } else {
                                        $order = Order::where('out_trade_no', $out_trade_no)->first();
                                    }

                                    //订单存在
                                    if ($order) {
                                        //系统订单退款中
                                        if ($order->pay_status == '5') {
                                            $trans_date = isset($return_select_res['trans_date'])?date('Y-m-d', strtotime($return_select_res['trans_date'])):'';
                                            $trans_time = isset($return_select_res['trans_time'])?date('H:i:s', strtotime($return_select_res['trans_time'])):'';
                                            $trade_no = $return_select_res['party_order_id']??'';
                                            $pay_time = $trans_date.' '.$trans_time;
                                            $buyer_pay_amount = isset($return_data['business_amt'])?$return_data['business_amt']:$return_data['refund_amt']; //实际退款金额
//                                            $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');
//                            $buyer_id = $data['buyerId'];
                                            $in_data = [
                                                'status' => '6',
                                                'pay_status' => 6,
                                                'pay_status_desc' => '已退款',
                                                'trade_no' => $trade_no,
                                                'pay_time' => $pay_time,
//                                'buyer_id' => $buyer_id,
                                                'refund_amount' => $order->refund_amount + $buyer_pay_amount,
                                            ];
                                            $update_re = Order::where('out_trade_no', $out_trade_no)->update($in_data);
                                            if (Schema::hasTable('order_items')) {
                                                $update_re = OrderItem::where('out_trade_no', $out_trade_no)->update($in_data);
                                            }
                                            if (!$update_re) {
//                                                Log::info('汇付退款回调，更新系统订单号失败');
//                                                Log::info($in_data);
                                            }

                                            //记录入退款表
                                            RefundOrder::create([
                                                'ways_source' => $order->ways_source,
                                                'type' => $order->ways_type,
                                                'refund_amount' => $order->total_amount,//退款金额
                                                'refund_no' => $out_trade_no . '123',//退款单号
                                                'store_id' => $order->store_id,
                                                'merchant_id' => $order->merchant_id,
                                                'out_trade_no' => $order->out_trade_no,
                                                'trade_no' => $order->trade_no
                                            ]);
                                            //退款成功后的操作
                                            RefundSuccessAction::action([
                                                'out_trade_no'=>$out_trade_no,
                                                'refund_no' => $out_trade_no . '123',//退款单号
                                            ]);
                                            //返佣去掉
                                            UserWalletDetail::where('out_trade_no', $out_trade_no)->update([
                                                'settlement' => '03',
                                                'settlement_desc' => '退款订单',
                                            ]);
                                            MerchantWalletDetail::where('out_trade_no', $out_trade_no)->update([
                                                'settlement' => '03',
                                                'settlement_desc' => '退款订单',
                                            ]);
                                        } else {
//                                            Log::info('汇付退款回调，没有正在退款的该系统订单号');
                                        }
                                    } else {
//                                        Log::info('汇付退款中回调，没有找到系统订单号');
                                    }
                                }
                            } else {
                                return json_encode([
                                    'code' => $return_select_res['status'],
                                    'msg' => $return_select_res['message'],
                                ]);
                            }
                        } else {
                            return json_encode([
                                'code' => $return_select_res['status'],
                                'msg' => $return_select_res['message'],
                            ]);
                        }
                    }

                } else{
                    return json_encode([
                        'code' => $data['resp_desc'],
                        'msg' => $data['resp_code'],
                    ]);
                }
            } else {
//                Log::info('退款回调没有值');
            }

            return json_encode([
                'code' => 'fail',
                'msg' => "汇付没有回调交易参数",
            ]);
        } catch (\Exception $exception) {
            Log::info('汇付退款交易异步报错');
            Log::info($exception);
        }
    }

}
